package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.constant.RedisConstants;
import com.hmdp.constant.UserConstant;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送短信验证码并保存验证码
     * @param phone
     * @param session
     */
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误");
        }

        //生成验证码
        String code = RandomUtil.randomNumbers(6);

        //保存验证码到redis
        stringRedisTemplate.opsForValue().set(RedisConstants.RedisUserConstants.LOGIN_CODE_KEY_PREFIX + phone,
                code,
                RedisConstants.RedisUserConstants.LOGIN_CODE_TTL,
                TimeUnit.MINUTES);

        // TODO 发送验证码
        log.debug("发送短信验证码成功，验证码：{}", code);

        return Result.ok();
    }

    /**
     * 登录功能
     * @param loginForm
     * @param session
     * @return
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //校验手机号
        if (RegexUtils.isPhoneInvalid(loginForm.getPhone())) {
            return Result.fail("手机号格式错误");
        }

        // 验证验证码
        String cacheCode = stringRedisTemplate.opsForValue().get(RedisConstants.RedisUserConstants.LOGIN_CODE_KEY_PREFIX + loginForm.getPhone());
        String inputCode = loginForm.getCode();
        if (cacheCode == null || !cacheCode.equals(inputCode)) {
            return Result.fail("验证码错误");
        }

        //根据手机号查询用户 select * from tb_user where phone = ?
        User user = lambdaQuery()
                .eq(User::getPhone, loginForm.getPhone())
                .one();

        //不存在，需要创建用户
        if (user == null) {
            user = createUserWithPhone(loginForm.getPhone());
        }

        //保存用户到redis
        String token = UUID.randomUUID().toString(true);
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO,
                new HashMap<>(),
                CopyOptions.create()
                    .setIgnoreNullValue(true)
                    .setFieldValueEditor((fieldName,fieldValue) -> fieldValue.toString()));
        stringRedisTemplate.opsForHash().putAll(RedisConstants.RedisUserConstants.LOGIN_USER_KEY_PREFIX + token,
                userMap);
        stringRedisTemplate.expire(RedisConstants.RedisUserConstants.LOGIN_USER_KEY_PREFIX + token,
                RedisConstants.RedisUserConstants.LOGIN_USER_TTL,
                TimeUnit.SECONDS);

        return Result.ok(token);
    }

    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(UserConstant.USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        save(user);
        return user;
    }

    @Override
    public Result sign() {
        //拼接签到key
        Long userId = UserHolder.getUser().getId();
        LocalDateTime now = LocalDateTime.now();
        String yyyyMM = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String signRedisKey = RedisConstants.RedisUserConstants.SIGN_KEY_PREFIX + userId.toString() + yyyyMM;

        //写入redis setbit key
        int dayOfMonth = now.getDayOfMonth();
        stringRedisTemplate.opsForValue().setBit(signRedisKey, dayOfMonth - 1, true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        //1、拼接签到key
        Long userId = UserHolder.getUser().getId();
        LocalDateTime now = LocalDateTime.now();
        String yyyyMM = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String signRedisKey = RedisConstants.RedisUserConstants.SIGN_KEY_PREFIX + userId.toString() + yyyyMM;

        //2、获取本月截止今天为止的签到记录，返回的是一个十进制的数字 bitfield sign:5:202504 get u3 0
        int dayOfMonth = now.getDayOfMonth();
        List<Long> resultList = stringRedisTemplate.opsForValue().bitField(
                signRedisKey,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth))
                        .valueAt(0)
        );
        if(CollUtil.isEmpty(resultList)){
            return Result.ok(0);
        }
        Long bitData = resultList.get(0);
        if (bitData == null || bitData == 0) {
            return Result.ok(0);
        }

        //3、计算累计签到次数
        int count = 0;
        //循环遍历
        while (true){
            //让这个数字与1做与运算、得到数字的最后-个bit位
            if ((bitData & 1) == 0) {
                //如果为0，说明未签到、结束
                break;
            }else {
                //如果不为0，说明己签到，计数器+1
                count++;
                //把数字右秘一位，抛弃最后一个bit位，继续下-个bit位
                bitData = bitData >>> 1;
            }

        }
        return Result.ok(count);
    }
}
